import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wms/utils/utils.dart';
import '/models/receiving_api_response.dart';
import 'package:http/http.dart' as http;
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart'; 
import 'dart:convert';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';

class ReceivingDetailItemScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;
  const ReceivingDetailItemScreen({super.key, required this.jsonData});

  @override
  State<ReceivingDetailItemScreen> createState() => _ReceivingDetailItemScreenState();
}

class _ReceivingDetailItemScreenState extends State<ReceivingDetailItemScreen> with WidgetsBindingObserver {
  // 选中的项值
  String? selectedItem;
  bool _isLoading = false;
  bool _isReadOnly = false;
  bool _isButtonEnabled = false;
  // 输入框控制器
  final _itemNumberController = TextEditingController();
  
  // 动态数据 - 本地数据源维护
  late Map<String, String> orderDetails;
  late List<String> availableItem;
  late List<ReceivingShipmentLine> originalOrderLines;
  Receivingobj? _receivingObj;
  ReceivingShipmentLine? selectedOrderLine;
  late String shipmentCode;
  String? itemNumber ;
  final FocusNode _barcodeFocusNode = FocusNode();

  // 新增：键盘控制核心变量（单个输入框，独立状态）
  bool _itemKeyboardVisible = false; // 当前输入框的键盘显示状态
  bool _isItemFocused = false;       // 当前输入框的焦点状态

  int? warehouseId;
  late double _fontScale ;

  // 字体尺寸定义
  double baseFontSize = 13;   // 标题/输入框字体基准
  double listFontSize = 12;   // 列表项字体基准

  // 统一样式定义
  TextStyle get _detailLabelStyle {
    return TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: 12 * _fontScale,
    );
  }

  TextStyle get _detailValueStyle {
    return TextStyle(
      fontSize: 12 * _fontScale,
    );
  }

  TextStyle get _listTitleStyle {
    return TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: baseFontSize * _fontScale,
    );
  }

  @override
  void initState() {
    super.initState();
    // 新增：注册应用生命周期监听（后台返回时重置键盘）
    WidgetsBinding.instance.addObserver(this);
    _initializeData();
    _itemNumberController.addListener(_updateButtonState);
    // 新增：初始化焦点监听（聚焦/失焦时同步键盘状态）
    _barcodeFocusNode.addListener(_handleItemFocusChange);

    // 新增：页面渲染后初始化键盘状态（避免初始异常）
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _resetAllKeyboards();
      }
    });
  }

  // 分离初始化逻辑
  void _initializeData() {
    try {
      // 解析传入的JSON数据
      _receivingObj = Receivingobj.fromJson(widget.jsonData);
      
      // 动态构建订单详情
      orderDetails = {
        'Order': _receivingObj?.orderInfo.orderNumber ?? 'N/A',
        'Order Type': _receivingObj?.orderInfo.orderType ?? 'N/A',
        'Container Number': _receivingObj?.totalLpns.toString() ?? 'N/A',
      };
      
      shipmentCode = _receivingObj?.shipmentCode ?? '';

      // 存储原始订单行数据
      originalOrderLines = _receivingObj?.receivingShipmentLines ?? [];

      // 动态构建可用项列表
      availableItem = originalOrderLines.map((orderLine) {
        return '${orderLine.itemNumber} | ${orderLine.orderPackQuantity} | ${orderLine.packType} | ${orderLine.itemName} | ${orderLine.status}';
      }).toList();
      
      // 初始化选中项
      if (availableItem.isNotEmpty) {
        selectedOrderLine = originalOrderLines.first;
        selectedItem = availableItem.first;
        _itemNumberController.text = selectedOrderLine!.itemNumber;
        _isButtonEnabled = true;
        // 调整：文本选中逻辑与焦点状态协调
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted && _barcodeFocusNode.hasFocus) {
            _itemNumberController.selection = TextSelection(
              baseOffset: 0,
              extentOffset: selectedOrderLine!.itemNumber.length,
            );
          }
        });
      }
    } catch (e) {
      // 初始化失败时显示错误信息
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          MessageBox.showMessageBox(context, 'Failed to initialize data: ${e.toString()}', isError: true);
        }
      });
    }
  }

  @override
  void dispose() {
    // 新增：移除生命周期监听和焦点监听
    WidgetsBinding.instance.removeObserver(this);
    _barcodeFocusNode.removeListener(_handleItemFocusChange);
    
    _itemNumberController.removeListener(_updateButtonState);
    _itemNumberController.dispose();
    _barcodeFocusNode.dispose();
    super.dispose();
  }

  // 新增：应用后台返回前台时重置键盘状态
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 新增：输入框焦点变化处理（聚焦弹键盘，失焦收键盘）
  void _handleItemFocusChange() {
    setState(() {
      _isItemFocused = _barcodeFocusNode.hasFocus;
    });

    if (_isItemFocused && !_itemKeyboardVisible) {
      // 聚焦时：显示键盘 + 同步控件状态
      _showKeyboard();
      setState(() => _itemKeyboardVisible = true);
    } else if (!_isItemFocused && _itemKeyboardVisible) {
      // 失焦时：隐藏键盘 + 同步控件状态
      _hideKeyboard();
      setState(() => _itemKeyboardVisible = false);
    }
  }

  // 新增：键盘显示/隐藏基础方法
  void _showKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.show');
      print('输入框键盘已显示');
    } catch (e) {
      print('显示键盘失败: $e');
    }
  }

  void _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      print('输入框键盘已隐藏');
    } catch (e) {
      print('隐藏键盘失败: $e');
    }
  }

  // 新增：切换输入框键盘状态（点击控件时调用）
  void _toggleItemKeyboard() {
    setState(() {
      _itemKeyboardVisible = !_itemKeyboardVisible;
    });

    if (_itemKeyboardVisible) {
      // 显示键盘：先聚焦输入框，再弹键盘
      _barcodeFocusNode.requestFocus();
      Future.delayed(const Duration(milliseconds: 100), () => _showKeyboard());
    } else {
      // 隐藏键盘：先失焦，再收键盘
      _barcodeFocusNode.unfocus();
      Future.delayed(const Duration(milliseconds: 100), () => _hideKeyboard());
    }
  }

  // 新增：重置所有键盘状态（点击空白区域时调用）
  void _resetAllKeyboards() {
    if (_itemKeyboardVisible || _isItemFocused) {
      setState(() {
        _itemKeyboardVisible = false;
        _isItemFocused = false;
      });
      _barcodeFocusNode.unfocus();
      _hideKeyboard();
    }
  }

  // 更新按钮状态
  void _updateButtonState() {
    final hasText = _itemNumberController.text.trim().isNotEmpty;
    if (_isButtonEnabled != hasText && !_isLoading) {
      setState(() {
        _isButtonEnabled = hasText;
      });
    }
  }

  // 处理项选择
  void _handleItemSelection(int index) {
    if (index < 0 || index >= originalOrderLines.length) return;
    
    final selectedLine = originalOrderLines[index];
    final selectedLpn = availableItem[index];
    
    setState(() {
      if (selectedOrderLine == selectedLine) {
        selectedOrderLine = null;
        selectedItem = null;
        _itemNumberController.clear();
      } else {
        selectedOrderLine = selectedLine;
        selectedItem = selectedLpn;
        _itemNumberController.text = selectedLine.itemNumber;
        
        // 选择项时：同步输入框选中状态（需确保焦点存在）
        if (_barcodeFocusNode.hasFocus) {
          _itemNumberController.selection = TextSelection(
            baseOffset: 0,
            extentOffset: selectedLine.itemNumber.length,
          );
        }
      }
    });
  }

  // 解析条形码
  void _parseBarcode(String value) {
    try {
      itemNumber = Utils.parseQRCode(value, 'item number');
      if (itemNumber != null) {
        setState(() {
          _itemNumberController.text = itemNumber.toString();
          // 解析后：同步输入框选中状态（需确保焦点存在）
          if (_barcodeFocusNode.hasFocus) {
            _itemNumberController.selection = TextSelection(
              baseOffset: 0,
              extentOffset: _itemNumberController.text.length,
            );
          }
        });
      }
    } catch (e) {
      if (mounted) {
        MessageBox.showMessageBox(context, e.toString(), isError: true);
      }
    }
  }

  // 移除选中项
  void _removeSelectedItem() {
    if (selectedOrderLine == null) return;

    setState(() {
      originalOrderLines.removeWhere((line) => 
        line.itemNumber == selectedOrderLine!.itemNumber &&
        line.id == selectedOrderLine!.id
      );

      availableItem = originalOrderLines.map((orderLine) {
        return '${orderLine.itemNumber} | ${orderLine.orderPackQuantity} | ${orderLine.packType} | ${orderLine.itemName} | ${orderLine.status}';
      }).toList();

      if (availableItem.isNotEmpty) {
        selectedItem = availableItem.first;
        selectedOrderLine = originalOrderLines.first;
        _itemNumberController.text = selectedOrderLine!.itemNumber;
        _isButtonEnabled = true;
        
        // 移除后：同步输入框选中状态（需确保焦点存在）
        if (_barcodeFocusNode.hasFocus) {
          _itemNumberController.selection = TextSelection(
            baseOffset: 0,
            extentOffset: selectedOrderLine!.itemNumber.length,
          );
        }
      } else {
        selectedItem = null;
        selectedOrderLine = null;
        _itemNumberController.text = '';
        _isButtonEnabled = false;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final mediaQuery = MediaQuery.of(context);
    final isSmallScreen = mediaQuery.size.width < 360;
    final textScaleFactor = isSmallScreen ? 0.85 : 1.0;
    
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    
    return MediaQuery(
      data: mediaQuery.copyWith(
        textScaler: TextScaler.linear(textScaleFactor),
      ),
      child: Scaffold(
        appBar: AppBar(
          title: Text('Receiving Detail', style: TextStyle(fontSize: 18 * _fontScale)),
          automaticallyImplyLeading: false,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            onPressed: () => Navigator.pushReplacementNamed(context, '/inbound/receiving'),
          ), 
          actions: [
            IconButton(
              icon: const Icon(Icons.home, color: Colors.white),
              onPressed: () => Navigator.pushReplacementNamed(context, '/home'),
            ),
          ],
          backgroundColor: const Color(0xFF008363),
        ),
        // 修改：点击空白区域时调用重置键盘方法（而非仅取消焦点）
        body: GestureDetector(
          onTap: () => _resetAllKeyboards(),
          behavior: HitTestBehavior.opaque,
          child: Padding(
            padding: EdgeInsets.all(isSmallScreen ? 16 : 32),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // 订单详情
                ..._buildOrderDetails(isSmallScreen),
                const SizedBox(height: 8),
                
                // 列表标题
                Text(
                  'Items:',
                  style: _listTitleStyle,
                ),
                const SizedBox(height: 8),
                
                // 列表区域
                Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey, width: 1.0),
                      borderRadius: BorderRadius.circular(4.0),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(4.0),
                      child: availableItem.isEmpty 
                          ? const Center(child: Text('No items available'))
                          : ListView.builder(
                              physics: const ClampingScrollPhysics(),
                              itemCount: availableItem.length,
                              itemBuilder: (context, index) {
                                final orderLine = originalOrderLines[index];
                                final currentItem = availableItem[index];
                                final isSelected = selectedItem == currentItem;

                                // Name标签样式：不加粗，与其他字段标签风格一致
                                final nameLabelStyle = TextStyle(
                                  fontSize: listFontSize * _fontScale,
                                  color: isSelected ? Colors.green : Colors.black87,
                                );
                                // Name值样式：保留加粗，与Item Number一致
                                final nameValueStyle = TextStyle(
                                  fontSize: listFontSize * _fontScale,
                                  fontWeight: FontWeight.bold,
                                  color: isSelected ? Colors.green : Colors.black87,
                                );

                                return InkWell(
                                  onTap: () {
                                    // 点击列表项时：先重置键盘，再处理选择
                                    _resetAllKeyboards();
                                    _handleItemSelection(index);
                                  },
                                  child: Container(
                                    margin: const EdgeInsets.symmetric(vertical: 2),
                                    decoration: BoxDecoration(
                                      border: Border.all(
                                        color: const Color.fromARGB(255, 169, 168, 168), 
                                        width: 0.5
                                      ),
                                      borderRadius: BorderRadius.circular(4.0),
                                      color: isSelected ? Colors.green[50] : null,
                                    ),
                                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
                                    // 上：Item Number（左） + Name:值（右，标签不加粗）；下：其他字段
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        // 上部分：Item Number（左） 和 Name:值（右）
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            // 1. Item Number（左对齐，加粗）
                                            Text(
                                              orderLine.itemNumber ?? 'N/A',
                                              style: TextStyle(
                                                fontSize: listFontSize * _fontScale,
                                                fontWeight: FontWeight.bold,
                                                color: isSelected ? Colors.green : Colors.black,
                                              ),
                                            ),
                                            // 2. Name:值（右对齐，标签不加粗，值加粗）
                                            Expanded(
                                              child: Padding(
                                                padding: const EdgeInsets.only(left: 12), // 与Item Number保持间距
                                                child: Row(
                                                  mainAxisAlignment: MainAxisAlignment.end, // 整体右对齐
                                                  children: [
                                                    // Name标签（不加粗）
                                                    Text(
                                                      'Name: ',
                                                      style: nameLabelStyle,
                                                    ),
                                                    // Name值（加粗，长文本省略）
                                                    Text(
                                                      orderLine.itemName ?? 'N/A',
                                                      style: nameValueStyle,
                                                      overflow: TextOverflow.ellipsis, // 长文本截断显示...
                                                      maxLines: 1, // 限制1行，避免换行影响布局
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                        const SizedBox(height: 5), // 上下分区间距
                                        
                                        // 下部分：Qty、Pack Type、Status（原有逻辑不变）
                                        Row(
                                          children: [
                                            // 字段1：Qty
                                            Expanded(
                                              flex: 1,
                                              child: Row(
                                                mainAxisSize: MainAxisSize.min,
                                                children: [
                                                  Text(
                                                    'Qty: ',
                                                    style: TextStyle(
                                                      fontSize: listFontSize * _fontScale,
                                                      color: isSelected ? Colors.green : Colors.black87,
                                                    ),
                                                  ),
                                                  Text(
                                                    '${orderLine.orderPackQuantity ?? 0}',
                                                    style: TextStyle(
                                                      fontSize: listFontSize * _fontScale,
                                                      color: isSelected ? Colors.green : Colors.black87,
                                                      fontWeight: FontWeight.bold,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            
                                            // 字段2：Pack Type
                                            Expanded(
                                              flex: 1,
                                              child: Row(
                                                mainAxisSize: MainAxisSize.min,
                                                children: [
                                                  Text(
                                                    'Pack Type: ',
                                                    style: TextStyle(
                                                      fontSize: listFontSize * _fontScale,
                                                      color: isSelected ? Colors.green : Colors.black87,
                                                    ),
                                                  ),
                                                  Text(
                                                    '${orderLine.packType ?? 'N/A'}',
                                                    style: TextStyle(
                                                      fontSize: listFontSize * _fontScale,
                                                      color: isSelected ? Colors.green : Colors.black87,
                                                      fontWeight: FontWeight.bold,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            
                                            // 字段3：Status
                                            Expanded(
                                              flex: 1,
                                              child: Row(
                                                mainAxisSize: MainAxisSize.min,
                                                children: [
                                                  Text(
                                                    'Status: ',
                                                    style: TextStyle(
                                                      fontSize: listFontSize * _fontScale,
                                                      color: isSelected ? Colors.green : Colors.black87,
                                                    ),
                                                  ),
                                                  Text(
                                                    '${orderLine.status ?? 'N/A'}',
                                                    style: TextStyle(
                                                      fontSize: listFontSize * _fontScale,
                                                      color: isSelected ? Colors.green : Colors.black87,
                                                      fontWeight: FontWeight.bold,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                    ),
                  ),
                ),
                
                const SizedBox(height: 12),
                
                // 输入区域（核心修改：添加键盘控件）
                _buildLpnInputSection(isSmallScreen),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 构建订单信息行
  List<Widget> _buildOrderDetails(bool isSmallScreen) {
    return orderDetails.entries.map((entry) {
      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 4),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              width: isSmallScreen ? 120 : 150,
              child: Text(
                '${entry.key}:',
                style: _detailLabelStyle,
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                entry.value,
                style: _detailValueStyle,
              ),
            ),
          ],
        ),
      );
    }).toList();
  }

  // 核心修改：输入框组件添加键盘控件
  Widget _buildLpnInputSection(bool isSmallScreen) {
    return Row(
      children: [
        Expanded(
          child: TextField(
            readOnly: _isReadOnly,
            keyboardType: TextInputType.text,
            controller: _itemNumberController,
            focusNode: _barcodeFocusNode,
            autofocus: false, // 禁用自动聚焦（避免初始弹键盘）
            decoration: InputDecoration(
              border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
              contentPadding: EdgeInsets.symmetric(
                horizontal: isSmallScreen ? 8 : 12,
                vertical: isSmallScreen ? 10 : 12,
              ),
              // 新增：键盘控制图标（与CheckinDetailScreen风格一致）
              suffixIcon: IconButton(
                icon: Icon(
                  _itemKeyboardVisible ? Icons.keyboard_hide : Icons.keyboard,
                  color: const Color(0xFF008363),
                  size: isSmallScreen ? 18 : 20,
                ),
                onPressed: _toggleItemKeyboard, // 绑定切换方法
                splashRadius: 20,
                padding: const EdgeInsets.all(4),
                constraints: const BoxConstraints.tightFor(width: 36, height: 36),
              ),
              // 新增：输入提示（根据键盘状态变化）
            ),
            style: TextStyle(fontSize: baseFontSize * _fontScale),
            onChanged: (value) => _updateButtonState(),
            onSubmitted: (value) => _handleSubmitted(value),
            onTap: () {
              // 点击输入框：选中全部文本（若有内容）
              if (_itemNumberController.text.isNotEmpty) {
                _itemNumberController.selection = TextSelection(
                  baseOffset: 0,
                  extentOffset: _itemNumberController.text.length,
                );
              }
              // 点击输入框时自动聚焦（触发焦点监听弹键盘）
              if (!_barcodeFocusNode.hasFocus) {
                _barcodeFocusNode.requestFocus();
              }
            },
          ),
        ),
        
        SizedBox(
          width: isSmallScreen ? 40 : 48,
          height: isSmallScreen ? 40 : 48,
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              padding: EdgeInsets.symmetric(
                horizontal: isSmallScreen ? 6 : 10,
                vertical: isSmallScreen ? 6 : 10,
              ),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(0.0),
              ),
              backgroundColor: _isButtonEnabled 
                          ? const Color(0xFF008363) 
                          : Colors.grey,
            ),
            onPressed: _isButtonEnabled && !_isLoading 
                ? () {
                    // 点击GO按钮时：先收起键盘，再提交
                    _resetAllKeyboards();
                    _handleSubmitted(_itemNumberController.text);
                  } 
                : null,
            child: _isLoading 
              ? const SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    color: Colors.white,
                  ),
                )
              : Text(
                'GO',
                style: TextStyle(
                  fontWeight: FontWeight.bold, 
                  fontSize: isSmallScreen ? 14 * _fontScale : 16 * _fontScale,
                  color: Colors.white
                ),
              ),
          ),
        ),
      ],
    );
  }

  // 提交处理方法（新增：提交前重置键盘）
  void _handleSubmitted(String value) async {
    if (!_isButtonEnabled || _isLoading || value.isEmpty) return;

    setState(() {
      _isLoading = true;
      _isReadOnly = true;
    });

    try {
      if (value.contains(':')) {
        _parseBarcode(value);
      }

      if (_receivingObj == null) {
        throw Exception('Receiving data is null');
      }

      final details = await _fetchPackDetail(
        shipmentCode: shipmentCode,
        itemNumber: selectedOrderLine?.itemNumber ?? itemNumber ?? value,
        internalItemNumber:selectedOrderLine?.internalItemNumber
      );
      
      if (!mounted) return;
      
      if (details['code'] == 2000) {
        final result = await Navigator.pushNamed(
          context,
          '/inbound/pack-detail',
          arguments: details
        );
        
        if (result == true && mounted) {
          setState(() {
            itemNumber = null;
            _itemNumberController.clear();
          });
          _removeSelectedItem();
        }
      } else {
        MessageBox.showMessageBox(context, details['msg'] ?? 'Unknown error', isError: true);
      }
    } catch (e) {
      if (mounted) {
        MessageBox.showMessageBox(context, e.toString(), isError: true);
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _isReadOnly = false;
        });
        // 新增：提交完成后重置键盘状态
        _resetAllKeyboards();
      }
    }
  }

  // 调用API获取详情
  Future<Map<String, dynamic>> _fetchPackDetail({
    required String shipmentCode,
    required String? itemNumber,
    required String? internalItemNumber,
  }) async {
    if (warehouseId == null) {
      throw Exception('Warehouse ID is not available');
    }

    final apiUrl = '${ApiService.baseURL}${ApiService.fetchPackDetail}?shipment_code=$shipmentCode&item_number=$itemNumber&internal_item_number=$internalItemNumber';

    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw Exception('Session expired. Please login again.');
    }
    
    try {
      print('url---$apiUrl');
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': warehouseId.toString(),
          'x-timezone': 'America/Los_Angeles',
          'X-Client-Type': 'app'
        },
      ).timeout(const Duration(seconds: 15));
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        return json.decode(responseBody);
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('API request failed: $e');
    }
  }
}